﻿using System;
using System.Collections;
using System.ComponentModel;
using System.Linq;
using System.Reflection;

namespace doufu.Common
{
    static public class AttributeExtension
    {
        public static bool AttributeExists<T>(this PropertyInfo propertyInfo) where T : class
        {
            var attribute = propertyInfo.GetCustomAttributes(typeof(T), false)
                                .FirstOrDefault() as T;
            if (attribute == null)
            {
                return false;
            }
            return true;
        }

        public static bool AttributeExists<T>(this Type type) where T : class
        {
            var attribute = type.GetCustomAttributes(typeof(T), false).FirstOrDefault() as T;
            if (attribute == null)
            {
                return false;
            }
            return true;
        }

        public static T GetAttribute<T>(this Type type) where T : class
        {
            return type.GetCustomAttributes(typeof(T), false).FirstOrDefault() as T;
        }

        public static T GetAttribute<T>(this PropertyInfo propertyInfo) where T : class
        {
            return propertyInfo.GetCustomAttributes(typeof(T), false).FirstOrDefault() as T;
        }

        public static string GetModelDesc<T>(this T model)
        {
            var type = model.GetType();
            return GetAttribute<DisplayNameAttribute>(type).GetProperty(x => x.DisplayName) ?? type.Name;
        }

        public static string DisplayName(this PropertyInfo src)
        {
            return src.GetAttribute<DisplayNameAttribute>().GetProperty(x => x.DisplayName) ?? src.Name;
        }

        public static string GetLabel(this IEnumerable Model)
        {
            var elementType = Model.GetType().GetElementType();
            if (elementType == null)
            {
                elementType = Model.GetType().GetGenericArguments()[0];
            }
            return elementType.Name;
        }

        //public static PropertyInfo[] VisibleProperties(this Object model)
        //{
        //    return model.GetType().GetProperties().Where(x => !x.AttributeExists<HiddenAttribute>()).ToArray();
        //}
    }
}